//
// Copyright © 2021 dev. All rights reserved.
//

import Foundation

final class PathUtil {
    static var bundleIdentifier = Bundle.main.bundleIdentifier

   static  var shouldUseDebugStorage:Bool {
    return UserDefaults.standard.bool(forKey: "WWDCUseDebugStorage")
    }

    enum AppSupportCreationError:Error {
        case fileExists
        var localizedDescription:String {
            switch self {
            case .fileExists:
                return "A file exists with the same name as the app support directory"
            }
        }
    }

    static var appSupportPathAssumingExisting:String {
        guard let identifier = bundleIdentifier else {
            fatalError("Bundle identifier is nil, this should never happen")
        }
        let dir:String

        #if AGENT
        dir = NSURL.realHomeDirectory()
            .appendingPathComponent("Library")
            .appendingPathComponent("Application Support")
            .path
        #else
        dir = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).first!
        #endif
        #if DEBUG
        var path = dir + "/\(identifier)"
        if shouldUseDebugStorage {
            path += ".debug"
        }
        #else
        let path = dir + "/\(identifier)"
        #endif
        return path
    }

    static func appSupportPathCreatingIfNeeded() throws -> String {
        let path = appSupportPathAssumingExisting
        var isDirectory:ObjCBool = false
        if !FileManager.default.fileExists(atPath: path,isDirectory: &isDirectory){
            try FileManager.default.createDirectory(atPath: path, withIntermediateDirectories: false, attributes: nil)
        }else {
            guard isDirectory.boolValue else {
                throw AppSupportCreationError.fileExists
            }
        }
        return path
    }

}
